package com.tianyang.yukuaifu.business.main.presenter;

import com.alibaba.fastjson.JSONObject;
import com.tianyang.yukuaifu.business.main.contract.MyContract;
import com.tianyang.yukuaifu.business.trade.bean.TradeFilterInput;
import com.tianyang.yukuaifu.business.trade.model.TradeModel;
import com.tianyang.yukuaifu.utils.DateUtils;

import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Description：我的presenter
 */

public class MyPresenter implements MyContract.Presenter {

    private MyContract.View mView;

    private CompositeSubscription mSubscription;

    public MyPresenter(MyContract.View mView) {
        this.mView = mView;
        mSubscription = new CompositeSubscription();
    }

    @Override
    public void getTradeRecordList() {
        TradeFilterInput input = new TradeFilterInput();
        input.setStartTime(DateUtils.getCurrentTime("yyyy-MM-dd"));
        input.setEndTime(DateUtils.getCurrentTime("yyyy-MM-dd"));
        input.setOrderStatus("0");
        Subscription subscription = TradeModel.getInstance()
                .merchantTradeDetail(1, input)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<JSONObject>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.showTradeTotalView(null);
                    }

                    @Override
                    public void onNext(JSONObject outputs) {
                        JSONObject obj = null;
                        if (outputs != null) {
                            obj = outputs.getJSONObject("obj");
                        }
                        mView.showTradeTotalView(obj);
                    }
                });
        mSubscription.add(subscription);
    }

    @Override
    public void onDestroyPresenter() {
        if (mView != null)
            mView = null;
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
            mSubscription = null;
        }
    }
}
